<!--
  * chenyuqiang
  *
  * @Author:    chenyuqiang
  * @Date:      2025-10-16 19:03:13
  * @Copyright  1
-->
<template>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item label="ip" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.ip" placeholder="ip" />
            </a-form-item>
            <a-form-item label="设备名称" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.deviceName" placeholder="设备名称" />
            </a-form-item>
            <a-form-item label="掩码" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.mask" placeholder="掩码" />
            </a-form-item>
            <a-form-item label="负责人" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.leader" placeholder="负责人" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="onSearch">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button @click="showForm" type="primary" size="small">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>
                <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table
            size="small"
            :scroll="{ x: 2000, y: 800 }"
            :dataSource="tableData"
            :columns="columns"
            rowKey="id"
            bordered
            :loading="tableLoading"
            :pagination="false"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
            :resizable="true"
            @resizeColumn="handleResize"
        >
            <template #bodyCell="{ text, record, column }">

                <template v-if="column.dataIndex === 'type'">
                    <DictLabel :dict-code="DICT_CODE_ENUM.CMDB_TYPE" :data-value="String(text)" />
                </template>

                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button @click="showForm(record)" type="link">编辑</a-button>
                        <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize"
                v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize"
                :total="total"
                @change="queryData"
                @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`"
            />
        </div>

        <CmdbForm  ref="formRef" @reloadList="queryData"/>

    </a-card>
</template>
<script setup>
    import { reactive, ref, onMounted } from 'vue';
import { useDictStore } from '/@/store/modules/system/dict.js';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { cmdbApi } from '/@/api/business/cmdb/cmdb-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import { DICT_CODE_ENUM } from '/@/constants/support/dict-const.js';
import { dictApi } from '/@/api/support/dict-api.js';
import CmdbForm from './cmdb-form.vue';
import DictLabel from '/@/components/support/dict-label/index.vue';

    // ---------------------------- 表格列宽调整相关 ----------------------------
    const COLUMN_WIDTH_STORAGE_KEY = 'cmdb-column-widths';

    // 处理列宽调整
    const handleResize = (width, column) => {
        const targetColumn = columns.value.find(col => col.dataIndex === column.dataIndex);
        if (targetColumn) {
            targetColumn.width = width;
            // 保存到本地存储
            const widths = JSON.parse(localStorage.getItem(COLUMN_WIDTH_STORAGE_KEY) || '{}');
            widths[column.dataIndex] = width;
            localStorage.setItem(COLUMN_WIDTH_STORAGE_KEY, JSON.stringify(widths));
        }
    };

    // 从本地存储加载列宽
    const loadColumnWidths = () => {
        const savedWidths = JSON.parse(localStorage.getItem(COLUMN_WIDTH_STORAGE_KEY) || '{}');
        columns.value.forEach(col => {
            if (savedWidths[col.dataIndex]) {
                col.width = savedWidths[col.dataIndex];
            }
        });
    };

    // ---------------------------- 表格列 ----------------------------

    const columns = ref([
        {
            title: '序号',
            dataIndex: 'id',
            width: 80,
            ellipsis: true,
            resizable: true,
        },
        // {
        //     title: '办公区域名称',
        //     dataIndex: 'name',
        //     ellipsis: true,
        // },
        {
            title: '设备名称',
            dataIndex: 'deviceName',
            width: 150,
            ellipsis: true,
            resizable: true,
        },
        {
            title: 'ip',
            dataIndex: 'ip',
            width: 120,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '掩码',
            dataIndex: 'mask',
            width: 120,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '负责人',
            dataIndex: 'leader',
            width: 100,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '设备类型',
            dataIndex: 'type',
            width: 120,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '安全域名称',
            dataIndex: 'hostName',
            width: 150,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '部门',
            dataIndex: 'deptName',
            width: 120,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: 160,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            width: 160,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '创建用户',
            dataIndex: 'createUser',
            width: 100,
            ellipsis: true,
            resizable: true,
        },
        {
            title: '修改用户',
            dataIndex: 'updateUser',
            width: 100,
            ellipsis: true,
            resizable: true,
        },
        
        
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 90,
            resizable: true,
        },
    ]);

    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        ip: undefined, //ip
        deviceName: undefined, //设备名称
        mask: undefined, //掩码
        leader: undefined, //负责人
        pageNum: 1,
        pageSize: 10,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);

    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    // 搜索
    function onSearch(){
      queryForm.pageNum = 1;
      queryData();
    }

    // 查询数据
    async function queryData() {
        tableLoading.value = true;
        try {
            let queryResult = await cmdbApi.queryPage(queryForm);
            console.log('CMDB Data:', queryResult.data.list);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }


    onMounted(async () => {
        // 加载保存的列宽
        loadColumnWidths();
        
        const dictStore = useDictStore();
        const dictRes = await dictApi.getAllDictData();
        dictStore.initData(dictRes.data);
        console.log('CMDB_TYPE Dict Data:', dictStore.getDictData(DICT_CODE_ENUM.CMDB_TYPE));
        queryData();
    });

    // ---------------------------- 添加/修改 ----------------------------
    const formRef = ref();

    function showForm(data) {
        formRef.value.show(data);
    }

    // ---------------------------- 单个删除 ----------------------------
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await cmdbApi.delete(data.id);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await cmdbApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }
</script>

<style scoped>
.smart-query-form {
    background: #fafafa;
    padding: 16px;
    margin-bottom: 16px;
    border-radius: 6px;
}

.smart-query-form-row {
    margin-bottom: 16px;
}

.smart-query-form-row:last-child {
    margin-bottom: 0;
}

.smart-table-btn-block {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.smart-margin-left10 {
    margin-left: 10px;
}

.smart-table-operate {
    display: flex;
    gap: 8px;
}

.smart-query-table-page {
    margin-top: 16px;
    text-align: right;
}

/* 添加拖拽列样式 */
:deep(.ant-table) {
    .ant-table-thead > tr > th {
        position: relative;
        transition: background 0.3s;
        
        &::after {
            content: '';
            position: absolute;
            right: 0;
            top: 25%;
            width: 2px;
            height: 50%;
            background-color: transparent;
            cursor: col-resize;
            transition: background-color 0.3s;
        }
        
        &:hover::after {
            background-color: #1890ff;
        }
    }
    
    .resizing {
        cursor: col-resize;
        user-select: none;
        
        &::after {
            background-color: #1890ff;
        }
    }

    .ant-table-cell {
        transition: width 0.3s;
    }
}
</style>
